package com.hyh.user.controller;


import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hyh.user.dao.UserMapper;
import com.hyh.user.domain.User;
import com.hyh.user.result.PageResult;
import com.hyh.user.util.CacheClient;
import com.hyh.user.util.CheckCodeUtil;
import com.hyh.user.util.RedisCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

/**
 * @description 管理员登录
 * @author hyh
 * @date  2024/4/15 22:25
 */

@RestController
@RequestMapping("/api/sys")
public class SysLoginController {

    @Autowired
    private CacheClient cacheClient;

    @Autowired
    private UserMapper userMapper;

    PasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    /**
     * @description 验证码
     * @param
     * @return
     * @author
     * @date  2024/4/15 22:27
     */
    @GetMapping("/generate")
    public void generateCaptcha(HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        OutputStream fos = response.getOutputStream();
        String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, fos, 4);
        cacheClient.set(RedisCodeUtil.LOGIN_SYS + checkCode,checkCode,RedisCodeUtil.LOGIN_CODE_KEY_TTL,TimeUnit.MINUTES);
    }


    /**
     * @description 登录
     * @param
     * @return
     * @date  2024/4/15 22:27
     */
    @PostMapping("/login")
    public PageResult login(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        String checkCode = cacheClient.get(RedisCodeUtil.LOGIN_SYS + user.getCheckCode());
        if (checkCode == null) {
            return new PageResult(HttpStatus.HTTP_CREATED, "验证码已过期");
        }
        if (!checkCode.equals(user.getCheckCode())) {
            return new PageResult(HttpStatus.HTTP_CREATED, "验证码错误");
        }
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        User user1 = userMapper.selectOne(qw.eq(User::getUsername, username));
        if (user1 == null) {
            return new PageResult(HttpStatus.HTTP_CREATED, "用户不存在");
        }
        if (!bCryptPasswordEncoder.matches(password, user1.getPassword())) {
            return new PageResult(HttpStatus.HTTP_CREATED, "密码错误");
        }
        return new PageResult(HttpStatus.HTTP_OK, null, "登陆成功");
    }
}
